package com.stone;/*

 */

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;


import java.io.IOException;

/**
 * 创建索引
 * @ClassName EsTest_Client
 * @Author Final
 * @Project DataStructures
 */
public class EsTest_Doc_Create {

    public static void main(String[] args) throws IOException {

        //创建客户端
        RestHighLevelClient esClient=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        //创建索引
        IndexRequest request = new IndexRequest("students");
        request.index("students").id("1001");

        Students students=new Students();
        students.setAge(12);
        students.setName("张三");
        students.setSex("男");

        //向es插入数据，必须将数据转换成json格式
        ObjectMapper mapper=new ObjectMapper();
        String userJson = mapper.writeValueAsString(students);
        request.source(userJson, XContentType.JSON);

        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);

        DocWriteResponse.Result result = response.getResult();
        System.out.println(result);
        //关闭es客户端
        esClient.close();
    }
}
